package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class My_Profile_Wishlist extends ListActivity {
	// List is a linked list
	// Map is a hash table: String -> Object
	private List<Map<String, Object>> mData;
	final Bundle extras = new Bundle();
	static final int WARNING_ID =0;
	ProgressThread progThread;
	final int SPINNER = 0;
	ProgressDialog progDialog;
	MyAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_profile_wishlist_main);
		String[] usernamePassword = LoginUtility.getUsernamePassword(My_Profile_Wishlist.this);
		String username = usernamePassword[0];
		
		List<NameValuePair> params = new ArrayList<NameValuePair>(1);
		params.add(new BasicNameValuePair("username", username));
		
		showDialog(SPINNER);
		progThread = new ProgressThread(mhandler,params, 0, 0);
		progThread.start();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Loading...");

			return progDialog;
		default:
			return null;
		}
	}

	// Handler on the main (UI) thread that will receive messages from the
	// second thread and update the progress.

	final Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			// Get the current value of the variable total from the message data
			// and update the progress bar.
			String returnedData = msg.getData().getString("returnedData");
			removeDialog(SPINNER);		
			int from = msg.getData().getInt("from");
			if(from == 0){
				if(returnedData.contains("error")){
					Toast.makeText(My_Profile_Wishlist.this, "Network Error", Toast.LENGTH_SHORT).show();
				}
				else{
					mData = getData(returnedData);
				
					adapter = new MyAdapter(My_Profile_Wishlist.this);
					setListAdapter(adapter);
				}
			}
			else if(from == 1){
				Intent myIntent = new Intent(My_Profile_Wishlist.this,
						ViewBookDetailsTab.class);
				myIntent.putExtra("data", returnedData);
				startActivity(myIntent);
			}
			else if(from == 2){
				int position = msg.getData().getInt("position");
				if(returnedData.contains("delete_successful")){
					mData.remove(position);
					Toast.makeText(My_Profile_Wishlist.this,"Deletion is successful.", Toast.LENGTH_SHORT).show();
					adapter.notifyDataSetChanged();
				}
				else if(returnedData.contains("delete_failed")){
					Toast.makeText(My_Profile_Wishlist.this,"Database Error. Operation failed.", Toast.LENGTH_SHORT).show();
				}
				else{
					Toast.makeText(My_Profile_Wishlist.this,"Network Error.Please check your network connection", Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	private class ProgressThread extends Thread {
		// Class constants defining state of the thread
		Handler mHandler;
		List<NameValuePair> params;
		int from;
		int position;

		ProgressThread(Handler h,List<NameValuePair> p, int f, int pos) {
			mHandler = h;
			params = p;
			from = f;
			position = pos;
		}

		@Override
		public void run() {
			Message msg = mHandler.obtainMessage();
			String returnedData;
			if(from == 0){
				returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/wishlist_display.jsp");
				
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
			else if(from == 1){
				returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/isbnsearch.jsp");
				
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}else if(from == 2){
				returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/wishlistremove.jsp");
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				b.putInt("position", position);
				b.putInt("from", from);
				msg.setData(b);
				mHandler.sendMessage(msg);
			}
		
		}

		// Set current state of thread (use state=ProgressThread.DONE to stop
		// thread)

	}
	

	private List<Map<String, Object>> getData(String data) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map ;
		//TODO
		
		try{
		    JSONArray jArray = new JSONArray(data);
		    JSONObject json_data=null;
		    int length = jArray.length();
		    for(int i = 0; i < length; i++){
		    json_data = jArray.getJSONObject(i);
		    map = new HashMap<String, Object>();
			map.put("title", json_data.getString("Title"));
			map.put("edition", json_data.getString("Edition"));
			map.put("courses", json_data.getString("Courses"));
			map.put("authors", json_data.getString("Authors"));
			map.put("publishers", json_data.getString("Publisher"));
			map.put("ISBN", json_data.getString("ISBN"));
			map.put("Date", json_data.getString("Date"));
			list.add(map);
		    }
		}catch (JSONException e) {
            throw new RuntimeException(e);
        }
		
		return list;
	}


	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		// Log.v("MyListView4-click", (String)mData.get(position).get("title"));
		List<NameValuePair> params = new ArrayList<NameValuePair>(1);
		params.add(new BasicNameValuePair("input", (String) mData.get(position).get("ISBN")));
		showDialog(SPINNER);
		progThread = new ProgressThread(mhandler,params, 1, 0);
		progThread.start();		
	}

	public class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}


		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}


		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}


		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public final class ViewHolder {
			public TextView title;
			public TextView edition;
			public TextView course;
			public TextView authors;
			public TextView publishers;
			public TextView ISBN;
			public Button remove;
			public TextView Date;

		}


		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {

				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.my_profile_wishlist, null);
				holder.title = (TextView) convertView.findViewById(R.id.tv_MyProfileWishlist_title);
				holder.edition = (TextView) convertView
						.findViewById(R.id.tv_MyProfileWishlist_edition);
				holder.course = (TextView) convertView
						.findViewById(R.id.tv_MyProfileWishlist_course);
				holder.authors = (TextView) convertView
						.findViewById(R.id.tv_MyProfileWishlist_authors);
				holder.publishers = (TextView) convertView
						.findViewById(R.id.tv_MyProfileWishlist_publishers);
				holder.ISBN = (TextView) convertView.findViewById(R.id.tv_MyProfileWishlist_ISBN);
				holder.remove = (Button) convertView.findViewById(R.id.b_MyProfileWishlist_remove);
				holder.Date = (TextView) convertView.findViewById(R.id.tv_MyProfileWishlist_Date);
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.title.setText((String) mData.get(position).get("title"));
			holder.edition.setText((String) mData.get(position).get("edition"));
			holder.course.setText((String) mData.get(position).get("courses"));
			holder.authors.setText((String) mData.get(position).get("authors"));
			holder.publishers.setText((String) mData.get(position).get(
					"publishers"));
			holder.ISBN.setText((String) mData.get(position).get("ISBN"));
			holder.Date.setText((String) mData.get(position).get("Date"));
			
			holder.remove.setTag(position);
			holder.remove.setOnClickListener(new View.OnClickListener() {
				

				public void onClick(final View v) {
					// TODO Auto-generated method stub
			    	AlertDialog.Builder builder = new AlertDialog.Builder(My_Profile_Wishlist.this);
			    	builder.setMessage("Are you sure you want to remove this book from wishlist?")
			    	       .setCancelable(false)
			    	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			    	           public void onClick(DialogInterface dialog, int id) {
									int position = Integer.parseInt(v.getTag().toString());
									String isbnStr = (String)mData.get(position).get("ISBN");
									String[] usernamePassword = LoginUtility.getUsernamePassword(My_Profile_Wishlist.this);
									String username = usernamePassword[0];
									
									List<NameValuePair> params = new ArrayList<NameValuePair>(2);
									params.add(new BasicNameValuePair("isbn", isbnStr));
									params.add(new BasicNameValuePair("username", username));
									showDialog(SPINNER);
									progThread = new ProgressThread(mhandler,params, 2, position);
									progThread.start();
			    	           }
			    	       })
			    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			    	           public void onClick(DialogInterface dialog, int id) {
			    	                dialog.cancel();
			    	           }
			    	       });
			    	AlertDialog alert = builder.create();
			    	alert.show();
				}
				
			});
			
			return convertView;
		}

	}
}
